package com.ethan.http;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.OnLifecycleEvent;

import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.BackpressureStrategy;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.core.FlowableEmitter;
import io.reactivex.rxjava3.core.FlowableOnSubscribe;
import io.reactivex.rxjava3.core.FlowableTransformer;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableSource;
import io.reactivex.rxjava3.core.ObservableTransformer;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.schedulers.Schedulers;

import static androidx.lifecycle.Lifecycle.Event.ON_DESTROY;
import static androidx.lifecycle.Lifecycle.Event.ON_STOP;

public class ApiFlowableTransformer<T extends BaseBean> implements ObservableTransformer<T,T>, LifecycleObserver {

    @OnLifecycleEvent(ON_DESTROY)
    void onDestroy(){
        if (!disposables.isDisposed()){
            disposables.clear();
        }

    }
    private Lifecycle lifecycle;

    public ApiFlowableTransformer(LifecycleOwner lifecycleOwner) {
        this.lifecycle = lifecycleOwner.getLifecycle();
        lifecycle.addObserver(this);
    }

    private final CompositeDisposable disposables = new CompositeDisposable();

    @Override
    public @NonNull ObservableSource<T> apply(@NonNull Observable<T> upstream) {
        return upstream.doOnSubscribe(v->disposables.add(v))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .flatMap(v->ApiFowable.creater(v));
    }

    public static <T extends BaseBean>  ApiFlowableTransformer<T>create(LifecycleOwner lifecycleOwner){
        return new ApiFlowableTransformer<T>(lifecycleOwner);

    }

}
